package com.maiji.cloud.entities.manager;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@NoArgsConstructor
@Data
@Accessors(chain=true)
@Table(name = "user")
public class User implements UserDetails {

    @TableId
    @Column(name = "uu_id", type = MySqlTypeConstant.VARCHAR, length = 50, isKey = true)
    private String uuId;

    @Column(name = "name", type = MySqlTypeConstant.VARCHAR, length = 20)
    private String name;

    @Column(name = "pwd", type = MySqlTypeConstant.VARCHAR)
    private String pwd;

    @Column(name = "execute_pwd", type = MySqlTypeConstant.VARCHAR)
    private String executePwd; // 执行密码

    @Column(name = "token", type = MySqlTypeConstant.VARCHAR, length = 90)
    private String token;

    @Column(name = "token_status", type = MySqlTypeConstant.BIT, length = 1)
    private Boolean tokenStatus; //token是否失效

    @Column(name = "add_date", type = MySqlTypeConstant.DATETIME)
    private Date addDate;

    @Column(name = "only_read", type = MySqlTypeConstant.BIT, length = 1)
    private Boolean onlyRead; // 是否只读

    @Column(name = "usable", type = MySqlTypeConstant.BIT, length = 1)
    private Boolean usable; // 是否可用，0-否，1-是

    @TableField(exist = false)
    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(Role::getName).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.pwd;
    }

    @Override
    public String getUsername() {
        return this.name;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.usable;
    }

}
